package com.qianya.oa.util;

import com.google.common.io.Files;
import com.qianya.oa.vo.UploadFileRespVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;

/**
 * 本地文件存储
 */
@Service
public class FileService {

    private static final String SLASH = "-";

    @Value("${qy.file.access-path-pattern}")
    private String accessPathPattern;

    @Value("${qy.file.upload-folder}")
    private String uploadFolder;


    /**
     * 保存文件
     *
     * @param newFileName
     * @throws IOException
     */
    private UploadFileRespVo save(String newFileName, MultipartFile file, String prefixFolder) throws IOException {
        //file.transferTo 方法调用时，判断如果是相对路径，则使用temp目录，为父目录
        //因此，实际保存位置为 
        // C:\Users\xxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\\uploads\img\xxx.jpg
        //一则，位置不对，二则没有父目录存在，因此会产生上述错误。这里使用绝对路径
        File destFile = new File(new File(uploadFolder).getAbsolutePath() + File.separator + prefixFolder + File.separator, newFileName);
        Files.createParentDirs(destFile);
        file.transferTo(destFile);
        UploadFileRespVo uploadFileRespDto = new UploadFileRespVo();
        uploadFileRespDto.setFileName(newFileName);
        uploadFileRespDto.setUrl(accessPathPattern.replace("**", "") + prefixFolder + "/" + newFileName);
        uploadFileRespDto.setOriginalFileName(file.getOriginalFilename());
        return uploadFileRespDto;
    }

    public UploadFileRespVo saveImg(String newFileName, MultipartFile file) throws IOException {
        String imgPrefixFolder = "img";
        return save(newFileName, file, imgPrefixFolder);
    }

    public UploadFileRespVo saveVideo(String newFileName, MultipartFile file) throws IOException {
        String videoPrefixFolder = "video";
        return save(newFileName, file, videoPrefixFolder);
    }

    public UploadFileRespVo saveMP3(String newFileName, MultipartFile file) throws IOException {
        String filePrefixFolder = "file";
        return save(newFileName, file, filePrefixFolder);
    }

    /**
     * 删除本地文件
     *
     * @param url
     * @throws RuntimeException
     */
    public void delete(String url) throws RuntimeException {

        File imgFile = new File(uploadFolder + url);

        if (imgFile.exists()) {
            imgFile.delete();
        }
    }

    /**
     * 生成一个文件名  {name}/yyyyMMddHHmmssSSS+5位随机数.ext
     */
    public static String getFileName(String name, String ext) {
        String fileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + "_" + RandomStringUtils.randomNumeric(5) + '.' + ext;
        if (name != null) {
            return name + SLASH + fileName;
        } else {
            return fileName;
        }
    }

    /**
     * 删除某个文件夹下的所有文件夹和文件
     *
     * @param path String
     * @return boolean 当且仅当此抽象路径名表示的文件存在且 是一个目录时，返回 true
     * @throws FileNotFoundException
     */
    public boolean deleteFiles(String path) throws FileNotFoundException {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory()) {
            file.delete();
        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File delfile = new File(path + SLASH + filelist[i]);
                if (!delfile.isDirectory()) {
                    delfile.delete();
                } else if (delfile.isDirectory()) {
                    deleteFiles(path + SLASH + filelist[i]);
                }
            }
            if (!file.toString().equals(uploadFolder)) { //不删除顶级目录
                file.delete();
            }
        }
        return true;
    }

    public static long getFileSize(String filename) {
        File file = new File(filename);
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在");
            return -1;
        }
        return file.length();
    }

    public String optimizeImgUrl(String imgUrl) {
        if (imgUrl.isEmpty() || !imgUrl.contains("e/")) {
            return imgUrl;
        }
        String str1 = imgUrl.substring(0, imgUrl.indexOf("e/"));
        String str2 = imgUrl.substring(str1.length() + 1, imgUrl.length());
        return str2;
    }
}
